import React from 'react';
import { Form, Input, message, Modal } from 'antd';
import { answerNodeAdd, answerNodeEdit } from '@/services/knowledgemanagement';

const AddOrEditNode = props => {

  /**
   * 确定按钮触发表单校验
   */
  const doSubmit = () => {
    props.form.validateFields(async (errors, values) => {
      if (errors) {
        return false;
      };
      switch (props.modalType) {
        case 'edit':
          const response = await answerNodeEdit({ name: values.name, id: props.currentNode.id });
          message.info(response.message);
          //新增成功后关闭弹窗并刷新树
          props.refreshTreeList(values.name);
          break;
        case 'add':
          const res = await answerNodeAdd({
            name: values.name,
            parentId: props.currentNode.id,
            parentPath: props.currentNode.parentPath
          });
          message.info(res.message);
          //新增成功后关闭弹窗并刷新树
          props.refreshTreeList();
          break;
      }
    })
  }
  /** 校验有效字段：提示语 */
  const checkFieldForCategoryName = (rule, value, callback) => {
    const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
    if (value) {
      if (reg.test(value)) {
        if (value.length > 20 || value.length < 0) {
          callback('支持20位以内大小写字母、数字和中文');
        } else {
          callback();
        }
      } else {
        callback('支持20位以内大小写字母、数字和中文');
      }
    } else {
      callback('支持20位以内大小写字母、数字和中文');
    }
  };
  const FormItemLayont = {
    labelCol: {
      xs: 24,
      sm: 5,
    },
    wrapperCol: {
      xs: 24,
      sm: 15,
    },
  };

  const { getFieldDecorator } = props.form;
  return (
    <Modal
      title={props.modalType === 'edit' ? '编辑分类' : '添加分类'}
      visible={props.visible}
      onCancel={props.cancelModal}
      onOk={doSubmit}
      destroyOnClose
    >
      <Form {...FormItemLayont}>
        <Form.Item label={'分类名'}>
          {
            getFieldDecorator('name', {
              rules: [
                { required: true, message: '分类名不能为空' },
                { validator: props.visible ? checkFieldForCategoryName : '' }
              ],
              initialValue: props.modalType === 'edit' ? props.currentNode.name : ''
            })(
              <Input onPressEnter={doSubmit} />
            )
          }
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default Form.create()(AddOrEditNode);
